package com.geek.base.system.controller;

import com.alibaba.fastjson.JSON;
import com.geek.base.common.bean.DataTableBean;
import com.geek.base.common.bean.ResponseBean;
import com.geek.base.common.enums.LogMsgs;
import com.geek.base.common.enums.LogType;
import com.geek.base.system.bean.SysRole;
import com.geek.base.system.bean.SysUser;
import com.geek.base.system.bean.SysUserRole;
import com.geek.base.system.service.SysUserService;
import com.geek.core.config.annotation.WebLog;
import com.geek.core.config.security.SecurityConfig;
import com.geek.tool.DataUtil;
import com.geek.tool.KeyGeneratorUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.catalina.authenticator.SavedRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @功能 系统用户控制器
 * @作者 MaxBill
 * @时间 2018年7月19日
 * @邮箱 maxbill1993@163.com
 */
@Controller
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/list")
    @WebLog(msgs = LogMsgs.USER_LIST, type = LogType.USER_LOG)
    public String listUser() {
        return "system/user_list";
    }

    @RequestMapping("/save")
    @WebLog(msgs = LogMsgs.USER_SAVE, type = LogType.USER_LOG)
    public String saveUser() {
        return "system/user_save";
    }

    @RequestMapping("/pass")
    @WebLog(msgs = LogMsgs.USER_PASS, type = LogType.USER_LOG)
    public String passUser() {
        return "system/user_pass";
    }

    @RequestMapping("/info")
    @WebLog(msgs = LogMsgs.USER_INFO, type = LogType.USER_LOG)
    public ModelAndView infoUser(HttpServletRequest request, ModelAndView mv) {
        SysUser user = (SysUser) request.getSession().getAttribute("sysUser");
        SysUser userInfo = this.sysUserService.selectUserByUserId(user.getUserId());
        mv.addObject("userInfo", userInfo);
        mv.setViewName("system/user_info");
        return mv;
    }

    @RequestMapping("/edit")
    @WebLog(msgs = LogMsgs.USER_EDIT, type = LogType.USER_LOG)
    public ModelAndView editUser(ModelAndView mv, String userId) {
        SysUser sysUser = this.sysUserService.selectUserByUserId(userId);
        mv.addObject("sysUser", sysUser);
        mv.setViewName("system/user_edit");
        return mv;
    }

    @RequestMapping("/role")
    @WebLog(msgs = LogMsgs.USER_ROLE, type = LogType.USER_LOG)
    public ModelAndView menuRole(ModelAndView mv, String userId) {
        mv.addObject("userId", userId);
        SysUserRole userRole = this.sysUserService.selectUserRoleByUserId(userId);
        if (null != userRole && !StringUtils.isEmpty(userRole.getRoleId())) {
            mv.addObject("roleId", userRole.getRoleId());
        } else {
            mv.addObject("roleId", "");
        }
        mv.addObject("userId", userId);
        mv.setViewName("system/user_role");
        return mv;
    }

    @ResponseBody
    @RequestMapping("/deal")
    public ResponseBean dealUser(HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        String flag = (String) request.getAttribute("flag");
        String msgs = (String) request.getAttribute("msgs");
        switch (flag) {
            case "s":
                responseBean.setData("/root");
                responseBean.setMsgs(msgs);
                break;
            case "f":
                responseBean.setMsgs(msgs);
                responseBean.setCode(302);
                break;
        }
        System.out.println(JSON.toJSON(responseBean));
        return responseBean;
    }


    @ResponseBody
    @RequestMapping("/config")
    @WebLog(msgs = LogMsgs.USER_CONFIG, type = LogType.USER_LOG)
    public ResponseBean configUser(String userId, String roleId) {
        ResponseBean responseBean = new ResponseBean();
        int insFlag = this.sysUserService.configUser(userId, roleId);
        if (insFlag == 1) {
            responseBean.setMsgs("用户角色授权成功");
        } else {
            responseBean.setMsgs("用户角色授权失败");
        }
        return responseBean;
    }

    @ResponseBody
    @RequestMapping("/insert")
    @WebLog(msgs = LogMsgs.USER_INSERT, type = LogType.USER_LOG)
    public ResponseBean insertUser(SysUser user) {
        ResponseBean responseBean = new ResponseBean();
        SysUser userTemp = this.sysUserService.selectUserByUserName(user.getUserName());
        if (null == userTemp) {
            user.setUserId(KeyGeneratorUtil.getUUIDKey());
            user.setUserSalt(KeyGeneratorUtil.getUUIDKey());
            user.setUserPass(new SecurityConfig().passwordEncoder().encode(user.getUserPass()));
            user.setUserHead("/image/head.png");
            String isUse = user.getUserStatus();
            if (!StringUtils.isEmpty(isUse) && "on".equals(isUse)) {
                user.setUserStatus("y");
            } else {
                user.setUserStatus("n");
            }
            user.setCreateUser(DataUtil.getUserName());
            user.setCreateTime(new Date());
            int insFlag = this.sysUserService.insertUser(user);
            if (insFlag == 1) {
                responseBean.setMsgs("新增用户成功");
            } else {
                responseBean.setMsgs("新增用户失败");
            }
        } else {
            responseBean.setMsgs("新增用户失败,该用户已存在");
        }
        return responseBean;
    }

    @ResponseBody
    @RequestMapping("/update")
    @WebLog(msgs = LogMsgs.USER_UPDATE, type = LogType.USER_LOG)
    public ResponseBean updateUser(SysUser user) {
        ResponseBean responseBean = new ResponseBean();
        String isUse = user.getUserStatus();
        if (!StringUtils.isEmpty(isUse) && "on".equals(isUse)) {
            user.setUserStatus("y");
        } else {
            user.setUserStatus("n");
        }
        user.setUpdateUser(DataUtil.getUserName());
        user.setUpdateTime(new Date());
        int updFlag = this.sysUserService.updateUser(user);
        if (updFlag == 1) {
            responseBean.setMsgs("编辑用户成功");
        } else {
            responseBean.setMsgs("编辑用户失败");
        }
        return responseBean;
    }


    @ResponseBody
    @RequestMapping("/delete")
    @WebLog(msgs = LogMsgs.USER_DELETE, type = LogType.USER_LOG)
    public ResponseBean deleteUser(String userId) {
        ResponseBean responseBean = new ResponseBean();
        int delFlag = this.sysUserService.deleteUser(userId);
        if (delFlag == 1) {
            responseBean.setMsgs("删除用户成功");
        } else {
            responseBean.setMsgs("删除用户失败");
        }
        return responseBean;
    }


    @ResponseBody
    @RequestMapping("/select")
    @WebLog(msgs = LogMsgs.USER_SELECT, type = LogType.USER_LOG)
    public DataTableBean selectUser(SysUser user, int page, int limit) {
        DataTableBean tableData = new DataTableBean();
        Page<SysUser> pager = PageHelper.startPage(page, limit);
        List<SysUser> roleList = this.sysUserService.selectUserList(user);
        tableData.setCode(200);
        tableData.setCount(pager.getTotal());
        tableData.setMsgs("");
        tableData.setData(roleList);
        return tableData;
    }

    @ResponseBody
    @RequestMapping("/change")
    @WebLog(msgs = LogMsgs.USER_CHANGE, type = LogType.USER_LOG)
    public ResponseBean changeUser(HttpServletRequest request, String oldPass, String newPass, String curPass) {
        ResponseBean responseBean = new ResponseBean();
        if (!newPass.equals(curPass)) {
            responseBean.setCode(0);
            responseBean.setMsgs("两次输入密码不一致");
        } else {
            SysUser user = (SysUser) request.getSession().getAttribute("sysUser");
            String userPass = new SecurityConfig().passwordEncoder().encode(curPass);
            if (new SecurityConfig().passwordEncoder().matches(oldPass, user.getUserPass())) {
                int updFlag = this.sysUserService.updateUser(new SysUser(user.getUserId(), userPass));
                if (updFlag == 1) {
                    responseBean.setMsgs("修改密码成功，请重新登录");
                } else {
                    responseBean.setCode(0);
                    responseBean.setMsgs("修改密码失败");
                }
            } else {
                responseBean.setCode(0);
                responseBean.setMsgs("旧密码输入错误");
            }
        }
        return responseBean;
    }

}
